package com.atguigu.flink0922.chapter11;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/10 11:19
 */
public class Flink02_Table_Connector_Kafka {
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        
        final StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        final Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
        tenv
            .connect(new Kafka()
                         .version("universal")
                         .topic("sensor")
                         .startFromLatest()
                         .property("group.id", "Flink02_Table_Connector_Kafka")
                         .property("bootstrap.servers", "hadoop162:9092")
            )
            .withFormat(new Json())
            .withSchema(schema)
            .createTemporaryTable("sensor");
        
        final Table table = tenv.from("sensor");
        table
            .groupBy($("id"))
            .select($("id"), $("vc").max().as("vc_max"))
            .execute()
            .print();
        
    }
}
